package com.swak.persistence.mybatis.filter;

import java.lang.reflect.Method;
import java.sql.Connection;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.plugin.Invocation;

import com.swak.persistence.dialect.Dialect;

public abstract class AbstractFilter implements Filter {

	@Override
	public Object filter(Invocation invocation, FilterChain chain) throws Throwable {
		if (this.support(invocation.getMethod())) {
			return this.doFilter(invocation, chain);
		}
		return chain.filter(invocation);
	}

	protected boolean support(Method method) {
		return true;
	}

	protected Dialect getDialect(final Executor executor) {
		try {
			Connection conn = executor.getTransaction().getConnection();
			return Dialect.getCachedDialect(conn);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	protected abstract Object doFilter(Invocation invocation, FilterChain chain) throws Throwable;
}
